<?php

namespace app\api\controller;

use app\admin\model\goods\Cate;
use app\common\controller\Api;
use app\common\library\token\driver\Redis;
use app\common\model\sales\CheckoutGoods;
use app\common\model\sales\Slip;
use think\Db;
use app\common\model\goods\Goods;
use app\common\model\count\Monitor;
use app\common\model\goods\GoodsHouseStock;
use think\Cache;

/**
 * 自动接口
 */
class Auto extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 库存监控
     *
     */
    public function monitorStock()
    {
//        new Redis();
//        $redis = new \Redis;
//        $redis->connect('127.0.0.1', 6379);
//        $monitor_time = $redis->get('monitor_time');
        $Monitor = new Monitor;
        $mrow = $Monitor->order('updatetime','DESC')->find();

        if (empty($mrow['updatetime']) || $mrow['updatetime'] < time()-$this->_countsite['deficiency_time']*3600) {
            ini_set('memory_limit','512M');    // 临时设置最大内存占用为3G
            set_time_limit(0);   // 设置脚本最大执行时间 为0 永不过期
//           echo 2;
//           dump(time());
//           dump($this->_site);
//           dump($this->_countsite);
//           dump($this->_countsite['deficiency_time']);
//           $ctime = time()-$this->_countsite['deficiency_time']*60;
//           dump($ctime);

//            $redis->set('monitor_time',time());
//
            echo '库存监控';
            echo '<br>';
            echo '--------';
//        dump($this->_countsite);
//        dump($this->_site);


            $Monitor = new Monitor;
            $list = $Monitor->where(array('is_monitor' => 1))->select();
//             dump($list);
            foreach ($list as $v) {
                $GoodsHouseStock = new GoodsHouseStock;
                $stock = $GoodsHouseStock->getfictstock($v['goods_id'], $v['storehouse_id']);
                if (!empty($v['stock_num']) && $v['stock_num'] < $stock) {
                    $Monitor = new Monitor;
                    $Monitor->save(array('is_error' => 1,'error_msg'=>'到达下限阀值;'.$v['error_msg'],'updatetime'=>time()), array('id' => $v['id']));
                    continue;
                }
                if (!empty($v['upper_num']) && $v['upper_num'] > $stock) {
                    $Monitor = new Monitor;
                    $Monitor->save(array('is_error' => 1,'error_msg'=>'到达上限阀值;'.$v['error_msg'],'updatetime'=>time()), array('id' => $v['id']));
                    continue;
                }
                if (!empty($v['keep_num'])) {
                   $row = CheckoutGoods::where(array('goods_id'=>$v['goods_id']))->find();
                   if($row){
                        $time = $row['createtime'];
                   }else{
                       $time = $v['createtime'];
                   }

                   if($time < time() - 86400* $v['keep_num']){
                       $Monitor = new Monitor;
                       $Monitor->save(array('is_error' => 1,'error_msg'=>'滞留时间过长;'.$v['error_msg'],'updatetime'=>time()), array('id' => $v['id']));
                   }
                    continue;
                }
                $Monitor = new Monitor;
                $Monitor->save(array('updatetime'=>time()), array('id' => $v['id']));
            }

        }
    }
    public function shopmonitor(){
        $house_id = Cache::get('house_id');
        $page = Cache::get('page');
        if(empty($house_id)){
            $house_id = 1;
            Cache::set('house_id',1);
        }
        if(empty($page)){
            $page = 0;
            Cache::set('page',1);
        }else{
            Cache::set('page',$page+1);
        }

        $hrow = Db::name('storehouse')->where(array('id'=>$house_id))->find();
        if(empty($hrow)){
            Cache::set('house_id',1);
            Cache::set('page',0);
            exit;
        }

        $goods = Db::name('goods_house_stock')
            ->alias('s')
            ->join('goods g','s.goods_id = g.id')
            ->where(array('storehouse_id'=>$house_id))
            ->limit($page*10,10)
            ->select();

        if (empty($goods)){
            Cache::set('house_id',$house_id+1);
            Cache::set('page',0);
            exit;
        }
//        exit;
        $number = [];
        foreach ($goods as $k=>$v){
            $number[] = $v['number'];
            $row = Db::name('purchase_enter_goods')->where(array('goods_id'=>$v['goods_id'],'status'=>2,'storehouse_id'=>$house_id))->order('id','DESC')->find();
            if(!empty($row)){
                $goods[$k]['enter_price'] = $row['unit_price'];
            }
        }


        $url =  config('site.syncurl').'/api/sync/batchprice';

        $json = curl_post($url,array(
            'numbers'=>implode(',',$number),
            'code'=>$hrow['code'],
            'appkey'=>config('site.appkey'),
        ));
        $json = json_decode($json,true);

        if($json['code'] == 1){
            foreach ($json['data'] as $v){
                foreach ($goods as $val){
                    if($v['spec_num'] == $val['number']){
                        $msg = '';
                        //对比库存值
                        if($val['stock'] >0){
                            $average = $val['balance']/$val['stock'];
                            if($average >$v['jxs_price']){
                                $msg .='库存平均价'.$average.'高于商城价格'.$v['jxs_price'];
                            }
                        }
                        //对比最新入库价格
                        if(isset($val['enter_price'])){
                            if($val['enter_price'] > $v['jxs_price']){
                                if(empty($msg)){
                                    $msg .='最新采购价格'.$val['enter_price'].'高于商城价格'.$v['jxs_price'];
                                }else{
                                    $msg .=',最新采购价格'.$val['enter_price'].'高于商城价格'.$v['jxs_price'];
                                }

                            }
                        }
                        if(!empty($msg)){
                            $rr = Db::name('shop_monitor')->where(array('goods_id'=>$val['goods_id'],'storehouse_id'=>$house_id))->find();
                            if(empty($rr)){
                                Db::name('shop_monitor')->insert(array(
                                    'goods_id'=>$val['goods_id'],
                                    'storehouse_id'=>$house_id,
                                    'error_msg'=>$msg,
                                    'updatetime'=>time(),
                                    'createtime'=>time(),
                                ));
                            }else{
                                Db::name('shop_monitor')->where(array('id'=>$rr['id']))->update(array(
                                    'error_msg'=>$msg,
                                    'updatetime'=>time(),
                                ));
                            }
                        }
                    }
                }
            }
        }
    }
    /**
     * 定时更新库存
     *
     */
    public function syncgoods(){
//        set_time_limit(0);
        $list = Db::name('goods')
            ->field('g.number,h.stock,s.code')
            ->alias('g')
            ->join('goods_house_stock h','g.id = h.goods_id')
            ->join('storehouse s','h.storehouse_id = s.id')
            ->where(array('sync_status'=>2))
            ->select();
        foreach ($list as $v){
            $url = config('site.syncurl') . '/api/sync/syncstock';
            curl_post($url, array(
                'spec_num' => $v['number'],
                'code' => $v['code'],
                'stock' => $v['stock'],
                'appkey' => config('site.appkey'),
            ));
        }
    }
    public function syncdelivery(){
        $time = time()-86400*3;
        $clists = Db::name('sales_checkout')->where(array('status'=>3,'createtime'=>array('<',$time)))->select();
        foreach ($clists as $v){
            Db::name('sales_checkout')->where(array('id'=>$v['id']))->update(array('status'=>4));

            $slip = new Slip();
            $srow = $slip->find($v['sales_slip_id']);
            if($srow['status'] == 4){  //如果在等待确认了 就判断是否完成
                $all_num = Db::name('sales_checkout')->where(array('sales_slip_id'=>$v['sales_slip_id'],'status'=>array('<',5)))->count();
                $suc_num =Db::name('sales_checkout')->where(array('sales_slip_id'=>$v['sales_slip_id'],'status'=>4))->count();

                if($all_num == $suc_num){
                    $slip = new Slip();
                    $slip->save(array('status'=>5),array('id'=>$v['sales_slip_id']));
                    Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'status'=>array('<',5)))->update(array('status'=>4));
                }
            }
        }


    }
}
